import {ChangeDetectorRef, Component, ElementRef} from '@angular/core';
import {AlertController, App, IonicPage, LoadingController, NavController, Platform} from 'ionic-angular';
import {Contacts} from "@ionic-native/contacts";

import {ClientListProvider} from "../../../providers/client/client-list/client-list.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {ClientIndividualProvider} from "../../../providers/client/client-individual/client-individual.provider";
import {ClientProspectiveProvider} from "../../../providers/client/client-prospective/client-prospective.provider";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";


import {ClientGender, LinkmanItem, LinkmanType, ClientType} from "../../../model/pages/client/client-list/contact-item";
import $ from "jquery";
import {JqScrollStopService} from "../../../services/common/jq-scroll-stop.service";

@IonicPage()
@Component({
    selector: 'page-client-list',
    templateUrl: 'client-list.html',
    providers: [
        Contacts,
        ClientListProvider,
        ClientIndividualProvider,
        ClientProspectiveProvider,
        MessageBushService,
        JqScrollStopService,
        TabsPage,
        SideMenuService
    ]
})

export class ClientListPage {
    contactList: LinkmanItem[];
    searchKeyword: string;
    alphas: { v: string, isCurrent: boolean }[];
    $content;
    dataScrollingStore: any = {};
    $indexItem: any;
    groupEleHeight = this.cProvider.vw(8.33);
    contactEleHeight = this.cProvider.vw(12.96);
    scrollContent;
    isContentScrolling:boolean;
    scrollContentStyle = {};
    scrollContentSourceEle;
    $contactIndexEle;
    scrollContentHeight;
    indexWrapperOffset: any;
    indexItemHeight: any;
    totalHeight: number;
    //偏移量
    offsetTopSingle = 0;//-this.cProvider.vw(0.5);
    alphaOffset = 0;
    tailPaddingBottom = 0;//this.cProvider.vw(13);
    currentPageContact: {
        list: LinkmanItem[]
    };
    isViewDidLoad = false;
    isLoaded :boolean = false;
    constructor(public tabsPage: TabsPage,
                public navCtrl: NavController,
                private sideMenuService: SideMenuService,
                public alertCtrl: AlertController,
                public cProvider: ClientListProvider,
                public loadCtr: LoadingController,
                public _elementRef: ElementRef,
                public platform: Platform,
                public scrollStopsService: JqScrollStopService,
                public changeRef: ChangeDetectorRef,
                public app: App) {

        this.currentPageContact = {
            list: []
        };

    }

    openRoot = (name, index) => this.openTab(name, index);

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name: name, index: index});
    }

    //region 生命周期函数
    ionViewDidLoad() {
        this.scrollStopsService.init();
        this.isViewDidLoad = true;
        this.alphas = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('').map(al => {
            return {
                v: al,
                isCurrent: false
            }
        });
        this.elementInit();
    }

    ionViewDidEnter() {

        const flag = MessageBushService.getMessage(MessageBushService.keys.clientListUpdated);
        if (flag == '1' && !this.isViewDidLoad) {
            this.getContactData(true, false);
        }
        MessageBushService.setMessage(MessageBushService.keys.clientListUpdated, '0');
        this.isViewDidLoad = false;
    }

    elementInit() {
        this.$content = $('page-client-list .content');
        setTimeout(() => {
            this.$indexItem = $('.contact-list-item');
            this.scrollContentSourceEle = $('page-client-list .scroll-content');
            this.$contactIndexEle = $('.contact-list-index');
            this.indexWrapperOffset = this.$contactIndexEle.find('.button-inner').offset();
            if(this.platform.is('ios')){
                this.indexWrapperOffset.top += 15;
            }
            let h = this.$indexItem.height();
            this.indexItemHeight = Math.floor(h);
            this.scrollContent = $('.contact-wrapper');
            this.scrollContentHeight = this.scrollContent.height();
            this.getContactData(true, true);
            this.setIndexEventHandle();
        }, 800);
    }

    //endregion

    //region 获取通讯录数据

    /**
     * 获取数据
     * @param {boolean} saveCache 不缓存数据
     * @param {boolean} takeCache 从缓存中取数据
     */
    getContactData(saveCache?: boolean, takeCache?: boolean) {
        this.isLoaded = false;
        // if (takeCache) {
        //     const list = localStorage.getItem('contactList');
        //     if (list) {
        //         this.contactList = JSON.parse(list);
        //         this.dataRender(this.contactList);
        //         this.isLoaded = true;
        //         return;
        //     }
        // }
        let loading = this.loadCtr.create({
            spinner: 'circles',
            content: "加载中",
        });
        loading.present();
        this.cProvider.getClientGroupList(this.searchKeyword).subscribe(contactItemList => {
                this.contactList = contactItemList.map(i => {
                    const data = new LinkmanItem();
                    data.title = i.name || i.groupName;
                    data.itemType = i.groupName ? LinkmanType.Group : LinkmanType.Client;
                    data.clientType = i.leadId ? ClientType.Prospective : ClientType.CoreClient;
                    data.id = i.clientId || i.leadId;
                    data.vipFlag = i.vipFlag;
                    data.vipFlagDesc = i.vipFlagDesc;
                    data.clientRole = i.clientRole;
                    data.occupationDesc = i.occupationDesc;
                    data.gender = ClientGender.Unknown;
                    if (i.gender == 'M') {
                        data.gender = ClientGender.Male;
                    } else if (i.gender == 'F') {
                        data.gender = ClientGender.Female;
                    }
                    data.avatar = this.cProvider.getClientAvatar(data);
                    data.total = i.total;
                    return data;
                });
                this.dataRender(this.contactList);
                if (saveCache) {
                    localStorage.setItem('contactList', JSON.stringify(this.contactList));
                } else {
                    localStorage.removeItem('contactList');
                }
                loading.dismiss();
                this.isLoaded = true;
            },
            () => {
                loading.dismiss();
            }
        );

    }

    //endregion

    //region 数据渲染
    getHeightByIndex(start: number, last: number) {
        let totalHeight = 0;
        for (let i = start; i < last; i++) {
            let item = this.contactList[i];
            let itemHeight = 0;
            if (item.itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight - this.offsetTopSingle;
            } else {
                itemHeight = this.contactEleHeight - this.offsetTopSingle;
            }
            totalHeight += itemHeight;
        }
        return totalHeight;
    }

    getContactListByIndex(index, startTop) {
        let currentList = [];
        let pHeight = startTop;
        let singleGreenHeight = 0;
        let i = index;
        for (let len = this.contactList.length; i < len; i++) {
            this.contactList[i].style = {};
            let itemHeight = 0;
            if (this.contactList[i].itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight;
            } else {
                itemHeight = this.contactEleHeight;
            }
            this.contactList[i].style.top = (pHeight + singleGreenHeight) + 'px';
            singleGreenHeight += itemHeight;
            currentList.push(this.contactList[i]);
            if (singleGreenHeight >= this.scrollContentHeight) break;
        }
        return {i: i + 1, list: currentList, lastTop: pHeight + singleGreenHeight};
    }

    getContactListByScreen(index): LinkmanItem[] {

        //region 计算上一页样式与数据
        let startGreenHeight = 0;
        const prevList: LinkmanItem[] = [];
        let prevStart = -1;
        if (index > 0) {
            let start = index - 1;
            let singleGreenHeight = 0;
            for (let i = start; i > -1; i--) {
                let itemData = this.contactList[i];
                itemData.style = {};
                let itemHeight = 0;
                if (this.contactList[i].itemType === LinkmanType.Group) {
                    itemHeight = this.groupEleHeight;
                } else {
                    itemHeight = this.contactEleHeight;
                }
                singleGreenHeight += itemHeight;
                prevList.push(itemData);
                if (singleGreenHeight >= this.scrollContentHeight) {
                    prevStart = i;
                    break;
                }
            }
        }
        if (prevStart > 0) {
            startGreenHeight = this.getHeightByIndex(0, prevStart);
        }
        prevList.reverse();
        let prevSingHeight = 0;
        prevList.forEach(item => {
            item.style.top = (startGreenHeight + prevSingHeight) + 'px';
            let itemHeight = 0;
            if (item.itemType === LinkmanType.Group) {
                itemHeight = this.groupEleHeight - this.offsetTopSingle;
            } else {
                itemHeight = this.contactEleHeight - this.offsetTopSingle;
            }
            prevSingHeight += itemHeight;
        });
        //endregion

        let startTop = startGreenHeight + prevSingHeight;
        let current = this.getContactListByIndex(index, startTop);
        let nextData = this.getContactListByIndex(current.i, current.lastTop);

        return prevList.concat(current.list).concat(nextData.list);
    }

    dataTotal = 0;

    dataRender(clientList: LinkmanItem[]) {
        if (!this.totalHeight || this.dataTotal != clientList.length) {
            let totalHeight = 0;
            this.contactList.forEach(i => {
                if (i.itemType === LinkmanType.Group) {
                    totalHeight += (this.groupEleHeight - this.offsetTopSingle);
                } else {
                    totalHeight += (this.contactEleHeight - this.offsetTopSingle);
                }
            });
            this.totalHeight = totalHeight + this.tailPaddingBottom;
        }

        this.currentPageContact.list = this.getContactListByScreen(0);
        this.dataTotal = clientList.length;
        this.scrollContent.scrollTop(0);
    }

    //endregion

    //region 搜索关键字
    inputKeyUp(e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            this.searchHandle();
        }
    }

    //搜索按钮点击搜索通讯录
    searchHandle() {
        this.getContactData(!this.searchKeyword, !this.searchKeyword);
    }

    //endregion

    //region 字母索引
    contentScrollStopped(){
        this.isContentScrolling = false;
    }

    setContentScrollingTimer = null;
    setContentScrolling() {

        const handler = () => {
            if (this.setContentScrollingTimer) {
                clearTimeout(this.setContentScrollingTimer);
            }
            this.setContentScrollingTimer = setTimeout( () => {
                this.setContentScrollingTimer = null;
                this.contentScrollStopped();
            }, 100);

            this.isContentScrolling = true;
            if (!this.dataScrollingStore.isAlphaIndexTouch) {
                const scrollTop = this.scrollContent.scrollTop();
                let groupItem: LinkmanItem;
                let foundIndex = 0;
                let totalTop = 0;
                for (let i = 0, max = this.contactList.length; i < max; i++) {
                    const itemTemp = this.contactList[i];
                    if (itemTemp.itemType === LinkmanType.Group) {
                        groupItem = itemTemp;
                        totalTop += (this.groupEleHeight - this.offsetTopSingle);
                    } else {
                        totalTop += (this.contactEleHeight - this.offsetTopSingle);
                    }
                    if (totalTop >= scrollTop + this.tailPaddingBottom) {
                        foundIndex = i;
                        break;
                    }
                }
                if (groupItem) {
                    this.setIndexStyleByAlpha(groupItem.title);
                    this.currentPageContact.list = this.getContactListByScreen(foundIndex);
                }

            }
        };
        this.scrollContent.bind('scroll', handler).data('ddf', handler);
    }

    setIndexStyleByAlpha(alpha) {
        if (!alpha) {
            alpha = this.alphas[0].v;
        }
        this.alphas.forEach((al, i) => {
            if (al.v === alpha) {
                this.alphas['selected'] = i;
                this.dataScrollingStore.preIndex = i;
            }
            al.isCurrent = al.v === alpha;
        });
    }


    //
    movingSetIndexPrames = [];
    setCurrentAlphaTimout;
    queueSetScreenClient(){
        if(this.movingSetIndexPrames.length){
            const p = this.movingSetIndexPrames[0];
            this.setScreenClientList.apply(this,p);
            this.movingSetIndexPrames.shift();
        }
        this.setCurrentAlphaTimout = setTimeout(() => {
            this.queueSetScreenClient();
        },100);
    }

    setLastScreenClient(){
        let param = this.movingSetIndexPrames[this.movingSetIndexPrames.length - 1];
        if(param){
            this.setScreenClientList.apply(this,param);
        }
    }

    /**
     * 手势上下滑动客户列表
     */
    setIndexEventHandle() {

        this.setCurrentIndex(0);

        const self = this;
        this.$content.unbind('touchstart').bind('touchstart', e => {
            e.stopPropagation();
            let event = e;
            if(e.originalEvent){
                event = e.originalEvent;
            }
            if (event.targetTouches && event.targetTouches.length === 1) {
                let touchX = event.touches[0].clientX;
                let touchY = event.touches[0].clientY;
                touchY += (touchY * self.alphaOffset);
                //手势触摸横向大于91.94时
                if (touchX > self.cProvider.vw(91.94) && !self.isContentScrolling) {
                    const deltaY = touchY - self.indexWrapperOffset.top;
                    let alphaIndex = -1;
                    if (deltaY <= 0) {
                        alphaIndex = 0;
                    } else {
                        alphaIndex = Math.round(deltaY / self.indexItemHeight);
                        // alphaIndex = Math.floor(deltaY / self.indexItemHeight);
                    }
                    self.dataScrollingStore.isAlphaIndexTouch = true;
                    if (self.dataScrollingStore.preIndex !== alphaIndex && alphaIndex > -1) {
                        self.setCurrentIndex(alphaIndex);
                        self.setScreenClientList(alphaIndex, self.groupEleHeight, self.contactEleHeight, self.scrollContent);
                        self.dataScrollingStore.preIndex = alphaIndex;
                    }
                } else {
                    self.setContentScrolling();
                }
            }
        });
        this.$contactIndexEle.unbind('touchmove').bind('touchmove',e => {
            e.stopPropagation();
            let event = e;
            if(e.originalEvent){
                event = e.originalEvent;
            }
            if (self.dataScrollingStore.isAlphaIndexTouch) {
                let touchY = event.touches[0].clientY;
                touchY += (touchY * self.alphaOffset);
                const deltaY = touchY - self.indexWrapperOffset.top;
                let alphaIndex = -1;
                if (deltaY <= 0) {
                    alphaIndex = 0;
                } else {
                    alphaIndex = Math.floor(deltaY / self.indexItemHeight);
                }
                if (self.dataScrollingStore.preIndex !== alphaIndex && alphaIndex > -1) {
                    self.setCurrentIndex(alphaIndex);
                    self.movingSetIndexPrames.push([
                        alphaIndex,
                        self.groupEleHeight,
                        self.contactEleHeight,
                        self.scrollContent
                    ]);
                    self.setScreenClientList(alphaIndex, self.groupEleHeight, self.contactEleHeight, self.scrollContent);
                    self.dataScrollingStore.preIndex = alphaIndex;
                }
            }
        });
        this.$content.unbind('touchend').bind('touchend', e => {
            self.dataScrollingStore.isAlphaIndexTouch = false;
            self.setLastScreenClient();
            self.movingSetIndexPrames = [];
            if(self.setCurrentAlphaTimout)clearTimeout(self.setCurrentAlphaTimout);
        });

    }

    getContactByLetter(letter: string) {
        for (let i = 0, len = this.contactList.length; i < len; i++) {
            const item = this.contactList[i];
            if (item.title === letter) {
                this.currentPageContact.list = this.getContactListByScreen(i);
                try{
                    this.changeRef.detectChanges();
                }catch(e){}
                break;
            }
        }
    }

    setCurrentIndex(index: number) {
        if (this.scrollContent)
            this.scrollContent.unbind('scroll');

        //参数检查
        if (index < 1) index = 0;
        if (index > this.alphas.length - 1) {
            index = this.alphas.length - 1;
        }

        let currentLetter = this.alphas[index];
        // 设置字母索引列表选中项样式
        const selectedIndex = this.alphas['selected'];
        if (selectedIndex > -1) {
            this.alphas[selectedIndex].isCurrent = false;
        }
        currentLetter.isCurrent = true;
        this.alphas['selected'] = index;
    }

    setScreenClientList(index: number, groupHeight?: number, clientHeight?: number, content?: any){
        if (!groupHeight || !clientHeight || !content) return;

        //参数检查
        if (index < 1) index = 0;
        if (index > this.alphas.length - 1) {
            index = this.alphas.length - 1;
        }
        let groups = this.contactList.filter(item => item.itemType === LinkmanType.Group);
        // 设置滚动列表位置
        let scrollTopHeight = 0;
        let contactGroupLocationAlpha;
        let detectiveLetter = this.alphas[0].v;
        // 查找不为空的分组以计算分组高度
        const foundNoneAlpha = (detectIndex) => {
            if (detectIndex < 1) return [];
            const setAlpha = this.alphas[detectIndex];

            let f = -1;
            for (let indexIn = 0; indexIn < groups.length; indexIn++) {
                if (groups[indexIn].title === setAlpha.v) {
                    contactGroupLocationAlpha = setAlpha.v;
                    f = indexIn;
                    detectiveLetter = setAlpha.v;
                    break;
                }
            }
            if (f > -1) {
                return groups.slice(0, f);
            } else {
                return foundNoneAlpha(detectIndex - 1);
            }
        };
        groups = foundNoneAlpha(index);
        groups.forEach(g => {
            if (g.total) {
                scrollTopHeight += groupHeight;
                // scrollTopHeight += (g.total * clientHeight);
                scrollTopHeight += (g.total * (clientHeight - 0.05));
            }
        });

        this.getContactByLetter.call(this,detectiveLetter);

        content.stop(true, true);
        content.animate({
                scrollTop: `${scrollTopHeight}px`
            },
            100,
            void 0);
    }

    //endregion

    //region 跳转
    goFavoritedList() {
        this.navCtrl.push('FavoriteListPage');
    }

    /**
     * 添加客户单击
     */
    clientAddHandle() {
        this.navCtrl.push('ClientsAddPage');
    }

    goImportContacts() {
        this.navCtrl.push('ClientImportContactsPage');
    }
    /**
     * 后退
     */
    backHandle() {
        this.navCtrl.pop();
    }

    //跳转客户详情页
    goToClientDetail(client: LinkmanItem) {
        if (client.clientType === ClientType.CoreClient) {
            const role = client.clientRole;
            /*if (role.indexOf('O') > -1) {
                this.navCtrl.push('HolderClientDetailPage', {
                    clientNum: client.id,
                    role: role
                })
            } else {
                this.navCtrl.push('InsuredClientDetailPage', {
                    clientNum: client.id,
                    role: role
                })
            }*/
            this.navCtrl.push('HolderClientDetailPage', {
                clientNum: client.id,
                role: role
            })

        } else if (client.clientType === ClientType.Prospective) {
            this.navCtrl.push('ClientDetailPage', {
                clientNum: client.id,
                occupationDesc: client.occupationDesc
            })
        }
    }

    //endregion


}
